package com.cpecc.controller.wuzi;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cpecc.manager.wuzi.BaoFeiManager;
import com.cpecc.manager.wuzi.FuJianManager;
import com.cpecc.manager.wuzi.HeTongManager;
import com.cpecc.manager.wuzi.JiYaoManager;
import com.cpecc.manager.wuzi.TuPianManager;
import com.cpecc.manager.wuzi.WuZiManager;
import com.cpecc.manager.wuzi.ZhengMingManager;
import com.cpecc.model.wuzi.BaoFei;
import com.cpecc.model.wuzi.FuJian;
import com.cpecc.model.wuzi.HeTong;
import com.cpecc.model.wuzi.JiYao;
import com.cpecc.model.wuzi.TuPian;
import com.cpecc.model.wuzi.WuZi;
import com.cpecc.model.wuzi.ZhengMing;

@Controller
@RequestMapping(value = "/wuzi")
public class FuJianController implements ServletContextAware{
	
	@Autowired
	private TuPianManager tuPianManager;
	
	@Autowired
	private WuZiManager wuZiManager;
	
	@Autowired
	private HeTongManager heTongManager;
	
	@Autowired
	private ZhengMingManager zhengMingManager;
	
	@Autowired
	private BaoFeiManager baoFeiManager;
	
	@Autowired
	private JiYaoManager jiYaoManager;
	
	@Autowired
	private FuJianManager fuJianManager;
	
	@Autowired
	private ServletContext servletContext;
	
	@Override
	public void setServletContext(ServletContext context) {
		this.servletContext  = context;
	}
	
	@RequestMapping(value = "/uploadForm")
	public ModelAndView uploadForm(String wuZiId,String type){
		ModelAndView mav=new ModelAndView();
		mav.addObject("wuZiId", wuZiId);
		mav.addObject("type", type);
		mav.setViewName("wuzi/uploadForm");
		return mav;
	}
	
	@RequestMapping(value = "/displayTuPian")
	public ModelAndView displayTuPian(String wuZiId){
		ModelAndView mav=new ModelAndView();
		WuZi wuZi=wuZiManager.get(wuZiId);
		mav.addObject("tuPianList", wuZi.getTuPians());
		mav.setViewName("wuzi/tuPianListAjax");
		return mav;
	}
	
	@RequestMapping(value="selFileList")
	public ModelAndView selFileList(String fileName,String type){
		ModelAndView mav=new ModelAndView();
		if(type!=null && type.equals("0")){
			//合同
			mav.addObject("fileList", heTongManager.list(fileName));
		}else if(type!=null && type.equals("2")){
			//证明
			mav.addObject("fileList", zhengMingManager.list(fileName));
		}
		mav.setViewName("wuzi/selFileListAjax");
		return mav;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/fuJianSave")
	public void fuJianSave(String otherId,String type,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response){
		if (!file.isEmpty()) {
			String path = this.servletContext.getRealPath("/upload/");
			String fileName = file.getOriginalFilename();
			String fileIcon = getFileIcon(request, fileName);
			String fileType = fileName.substring(fileName.lastIndexOf("."));		
			String xinName = "";
			String format="yyyyMMdd";
			SimpleDateFormat sdf=new SimpleDateFormat(format);
			String rq=sdf.format(new Date());
			xinName+=rq;
			xinName += new Date().getTime();
			File file2 = new File(path, xinName + fileType);			
			try {
				file.getFileItem().write(file2);				
			} catch (Exception e) {
				e.printStackTrace();
			}
			JSONArray ja = new JSONArray();
			JSONObject json = new JSONObject();
			json.put("name", fileName);
			json.put("size", file.getSize());
			JSONObject js = new JSONObject();
			if(type!=null && type.equals("0")){
				HeTong heTong=new HeTong();
				heTong.setYsWJM(fileName);
				heTong.setWenJianM(xinName+fileType);
				heTong.setXiangDuiLJ("/upload");
				heTongManager.save(heTong);
				
				json.put("url", "/wuzi/downloadFile.do?id="+heTong.getId()+"&type=0");
				json.put("fuJianId", heTong.getId());
				json.put("type", "0");
				json.put("thumbnailUrl", "/wuzi/downloadFile.do?id="+heTong.getId()+"&type=0");
				json.put("deleteUrl", "/wuzi/delFuJian.do?id="+heTong.getId()+"&type=0");
				json.put("deleteType", "DELETE");
				json.put("fileIcon", fileIcon);
				ja.add(json);
				js.put("files", ja);
				js.put("fuJianId", heTong.getId());
				js.put("ysWJM", heTong.getYsWJM());
			}else if(type!=null && type.equals("2")){
				ZhengMing zhengMing=new ZhengMing();
				zhengMing.setYsWJM(fileName);
				zhengMing.setWenJianM(xinName+fileType);
				zhengMing.setXiangDuiLJ("/upload");
				zhengMingManager.save(zhengMing);
				
				json.put("url", "/wuzi/downloadFile.do?id="+zhengMing.getId()+"&type=2");
				json.put("fuJianId", zhengMing.getId());
				json.put("type", "0");
				json.put("thumbnailUrl", "/wuzi/downloadFile.do?id="+zhengMing.getId()+"&type=2");
				json.put("deleteUrl", "/wuzi/delFuJian.do?id="+zhengMing.getId()+"&type=2");
				json.put("deleteType", "DELETE");
				json.put("fileIcon", fileIcon);
				ja.add(json);
				js.put("files", ja);
				js.put("fuJianId", zhengMing.getId());
				js.put("ysWJM", zhengMing.getYsWJM());
			}else if(type!=null && type.equals("1")){
				TuPian tuPian=new TuPian();
				tuPian.setYsWJM(fileName);
				tuPian.setWenJianM(xinName+fileType);
				tuPian.setXiangDuiLJ("/upload");
				tuPian.setWuZi(wuZiManager.get(otherId));
				tuPianManager.save(tuPian);
				
				json.put("url", "/wuzi/downloadFile.do?id="+tuPian.getId()+"&type=1");
				json.put("fuJianId", tuPian.getId());
				json.put("thumbnailUrl", "/wuzi/downloadFile.do?id="+tuPian.getId()+"&type=1");
				json.put("deleteUrl", "/wuzi/delFuJian.do?id="+tuPian.getId()+"&type=1");
				json.put("deleteType", "DELETE");
				json.put("fileIcon", fileIcon);
				ja.add(json);
				js.put("files", ja);
				js.put("fuJianId", tuPian.getId());
				js.put("ysWJM", tuPian.getYsWJM());
			}else if(type!=null && type.equals("6")){
				//报废会议纪要
				JiYao jiYao=new JiYao();
				jiYao.setYsWJM(fileName);
				jiYao.setWenJianM(xinName+fileType);
				jiYao.setXiangDuiLJ("/upload");
				jiYaoManager.save(jiYao);
				
				json.put("url", "/wuzi/downloadFile.do?id="+jiYao.getId()+"&type=6");
				json.put("fuJianId", jiYao.getId());
				json.put("thumbnailUrl", "/wuzi/downloadFile.do?id="+jiYao.getId()+"&type=6");
				json.put("deleteUrl", "/wuzi/delFuJian.do?id="+jiYao.getId()+"&type=6");
				json.put("deleteType", "DELETE");
				json.put("fileIcon", fileIcon);
				ja.add(json);
				js.put("files", ja);
				js.put("fuJianId", jiYao.getId());
				js.put("ysWJM", jiYao.getYsWJM());
			}else if(type!=null && type.equals("7")){
				//报废附件
				FuJian fuJian=new FuJian();
				BaoFei baoFei=baoFeiManager.get(otherId);
				fuJian.setBaoFei(baoFei);
				fuJian.setWenJianM(xinName+fileType);
				fuJian.setXiangDuiLJ("/upload");
				fuJian.setYsWJM(fileName);
				fuJianManager.save(fuJian);
				
				json.put("url", "/wuzi/downloadFile.do?id="+fuJian.getId()+"&type=7");
				json.put("fuJianId", fuJian.getId());
				json.put("thumbnailUrl", "/wuzi/downloadFile.do?id="+fuJian.getId()+"&type=7");
				json.put("deleteUrl", "/wuzi/delFuJian.do?id="+fuJian.getId()+"&type=7");
				json.put("deleteType", "DELETE");
				json.put("fileIcon", fileIcon);
				ja.add(json);
				js.put("files", ja);
				js.put("fuJianId", fuJian.getId());
				js.put("ysWJM", fuJian.getYsWJM());
			}
			js.put("type", type);
			try {
				response.setContentType("application/json;charset=utf-8");
				response.getWriter().write(js.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value = "/delFuJian")
	public void delFuJian(String id,String type,HttpServletResponse response){
		if(type!=null && type.equals("0")){
			HeTong heTong=heTongManager.get(id);
			if(heTong!=null && heTong.getCaiGou()==null){
				try {
					String path = this.servletContext.getRealPath("/upload/");
					File file=new File(path+"\\"+heTong.getWenJianM());
					file.delete();
					heTongManager.delete(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if(type!=null && type.equals("2")){
			ZhengMing zhengMing=zhengMingManager.get(id);
			if(zhengMing!=null && zhengMing.getCaiGou()==null){
				try {
					String path = this.servletContext.getRealPath("/upload/");
					File file=new File(path+"\\"+zhengMing.getWenJianM());
					file.delete();
					zhengMingManager.delete(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if(type!=null && type.equals("1")){
			TuPian tuPian=tuPianManager.get(id);
			if(tuPian!=null){
				try {
					String path = this.servletContext.getRealPath("/upload/");
					File file=new File(path+"\\"+tuPian.getWenJianM());
					file.delete();
					tuPianManager.delete(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if(type!=null && type.equals("6")){
			JiYao jiYao=jiYaoManager.get(id);
			if(jiYao!=null && jiYao.getBaoFei()==null){
				try {
					String path = this.servletContext.getRealPath("/upload/");
					File file=new File(path+"\\"+jiYao.getWenJianM());
					file.delete();
					jiYaoManager.delete(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if(type!=null && type.equals("7")){
			FuJian fuJian=fuJianManager.get(id);
			if(fuJian!=null && fuJian.getBaoFei()==null){
				try {
					String path = this.servletContext.getRealPath("/upload/");
					File file=new File(path+"\\"+fuJian.getWenJianM());
					file.delete();
					fuJianManager.delete(id);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		try {
			response.setContentType("application/json;charset=utf-8");
			String result="{\"result\":\"success\"}";
			response.getWriter().write(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/downloadFile")
	public void downloadFile(String id, int type,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String path = this.servletContext.getRealPath("/upload/");
		String downLoadPath="";
		String ysWJM="";
		if(type==0){
			HeTong heTong=heTongManager.get(id);
			downLoadPath=path+"\\"+heTong.getWenJianM();
			ysWJM=heTong.getYsWJM();
		}else if(type==2){
			ZhengMing zhengMing=zhengMingManager.get(id);
			downLoadPath=path+"\\"+zhengMing.getWenJianM();
			ysWJM=zhengMing.getYsWJM();
		}else if(type==1){
			TuPian tuPian=tuPianManager.get(id);
			downLoadPath=path+"\\"+tuPian.getWenJianM();
			ysWJM=tuPian.getYsWJM();
		}else if(type==6){
			JiYao jiYao=jiYaoManager.get(id);
			downLoadPath=path+"\\"+jiYao.getWenJianM();
			ysWJM=jiYao.getYsWJM();
		}else if(type==7){
			FuJian fuJian=fuJianManager.get(id);
			downLoadPath=path+"\\"+fuJian.getWenJianM();
			ysWJM=fuJian.getYsWJM();
		}
		try {
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			ysWJM = ysWJM.replaceAll("\\s", "");
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(ysWJM.getBytes("utf-8"),"ISO-8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	private String getFileIcon(HttpServletRequest request, String fileName) {
		if (!StringUtils.hasText(fileName)) {
			return null;
		}

		String icon = null;
		int index = fileName.lastIndexOf('.');
		String suffix = fileName.substring(index + 1).toLowerCase();
		if ("doc".equals(suffix) || "docx".equals(suffix)) {
			icon = "u-word.png";
		} else if ("xls".equals(suffix) || "xlsx".equals(suffix)) {
			icon = "u-excel.png";
		} else if ("ppt".equals(suffix) || "pptx".equals(suffix)) {
			icon = "u-ppt.png";
		} else if ("pdf".equals(suffix)) {
			icon = "u-pdf.png";
		} else {
			icon = "u-doc.png";
		}
		return request.getContextPath() + "/assets/img/upload/" + icon;
	}
}
